package org.dingfugui.triple.connection.bio;

import org.dingfugui.triple.connection.Connection;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by fugui.ding on 2015/3/23.
 */
public class BioConnection implements Connection {

    protected Socket socket;

    public BioConnection(Socket socket) {
        this.socket = socket;
    }

    @Override
    public byte[] read() {
        InputStream in;
        try {
            in = socket.getInputStream();

            int count = 0;
            while (count == 0) {
                count = in.available();
            }
            byte[] result = new byte[count];
            in.read(result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void write(byte[] data) {
        try {
            OutputStream out = socket.getOutputStream();
            out.write(data);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isClose() {
        return socket.isClosed();
    }
}
